package com.chenwc.util.translate.google.v3;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.chenwc.util.httputil.httpclient.RestMockByProxy;
import com.chenwc.util.translate.google.oauth2.GoogleTranslateOauth2Util;
import com.chenwc.util.translate.google.oauth2.Oauth2Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Google翻译V3工具类
 *
 * @author chenwc
 * @date 2024/7/29
 */
public class GoogleTranslateV3Utils {

    private static final Logger logger = LoggerFactory.getLogger(GoogleTranslateV3Utils.class);

    private static String accessToken;

    /**
     * 翻译单个文本
     *
     * @param text           待翻译的文本
     * @param sourceLanguage 源语言
     * @param targetLanguage 目标语言
     * @return 翻译结果
     */
    public static String translateText(String text, SupportedLanguagesV3Code sourceLanguage, SupportedLanguagesV3Code targetLanguage) {
        JSONObject sendJson = new JSONObject();
        sendJson.put("contents", text);
        sendJson.put("mimeType", "text/plain");
        sendJson.put("source_language_code", sourceLanguage.getLanguageCode());
        sendJson.put("target_language_code", targetLanguage.getLanguageCode());
        JSONObject transliterationConfig = new JSONObject();
        transliterationConfig.put("enable_transliteration", true);
        sendJson.put("transliteration_config", transliterationConfig);

        logger.info("请求报文: {}", sendJson.toJSONString());
        Map<String, String> headers = getHeaders();
        headers.put("Content-Type", "application/json");
        logger.debug("请求头: {}", JSON.toJSONString(headers));

        String url = String.format(V3Constant.TRANSLATE_TEXT_URL, V3Constant.PROJECT_ID, V3Constant.LOCATIONS);
        String result = RestMockByProxy.sendPostByBody(url, headers, sendJson.toJSONString(), true);
        JSONObject resultJson = JSONObject.parseObject(result);
        logger.info("响应报文: {}", resultJson.toJSONString());
        JSONArray resultJsonArray = resultJson.containsKey("translations") ? resultJson.getJSONArray("translations") : new JSONArray();
        if (!resultJsonArray.isEmpty()) {
            // 默认返回第一条翻译结果
            return resultJsonArray.getJSONObject(0).getString("translatedText");
        }
        return null;
    }


    /**
     * 获取请求头
     *
     * @return 请求头
     */
    private static Map<String, String> getHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", Oauth2Constant.TOKEN_PREFIX + GoogleTranslateOauth2Util.getAccessToken());
        headers.put("x-goog-user-project", V3Constant.PROJECT_ID);
        headers.put("Host", "translation.googleapis.com");
        headers.put("Accept", "*/*");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Connection", "keep-alive");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");
        return headers;
    }

    /**
     * 获取支持的语言列表
     *
     * @return 支持的语言列表
     */
    public static List<Map<String, String>> listSupportedLanguages() {
        Map<String, String> headers = getHeaders();
        String url = String.format(V3Constant.GET_SUPPORTED_LANGUAGES_URL, V3Constant.PROJECT_ID, V3Constant.LOCATIONS);
        String result = RestMockByProxy.sendGetByParameter(url, headers, true);
        JSONObject resultJson = JSONObject.parseObject(result);
        logger.info("响应报文: {}", resultJson.toJSONString());
        JSONArray resultJsonArray = resultJson.containsKey("languages") ? resultJson.getJSONArray("languages") : new JSONArray();
        List<Map<String, String>> resultList = new ArrayList<>();
        if (!resultJsonArray.isEmpty()) {
            for (int i = 0; i < resultJsonArray.size(); i++) {
                JSONObject jsonObject = resultJsonArray.getJSONObject(i);
                Map<String, String> map = new HashMap<>();
                map.put("languageCode", jsonObject.getString("languageCode"));
                map.put("supportSource", jsonObject.getString("supportSource"));
                map.put("supportTarget", jsonObject.getString("supportTarget"));
                resultList.add(map);
            }
            return resultList;
        }
        return resultList;
    }

    /**
     * 检测语言
     *
     * @param text 待检测的语言
     * @return 检测结果。languageCode 提供检测到的语言的代码。confidence 的范围从 0 到 1。1 表示置信度为 100%。
     */
    public static List<Map<String, String>> detectLanguage(String text) {
        JSONObject sendJson = new JSONObject();
        sendJson.put("content", text);
        Map<String, String> headers = getHeaders();
        headers.put("Content-Type", "application/json");
        logger.debug("请求头: {}", JSON.toJSONString(headers));

        String url = String.format(V3Constant.DETECT_LANGUAGES_URL, V3Constant.PROJECT_ID, V3Constant.LOCATIONS);
        String result = RestMockByProxy.sendPostByBody(url, headers, sendJson.toJSONString(), true);
        JSONObject resultJson = JSONObject.parseObject(result);
        logger.info("响应报文: {}", resultJson.toJSONString());
        JSONArray languages = resultJson.containsKey("languages") ? resultJson.getJSONArray("languages") : new JSONArray();
        List<Map<String, String>> resultMapList = new ArrayList<>();
        if (!languages.isEmpty()) {
            for (int i = 0; i < languages.size(); i++) {
                Map<String, String> resultMap = new HashMap<>();
                JSONObject jsonObject = languages.getJSONObject(i);
                resultMap.put("languageCode", jsonObject.getString("languageCode"));
                resultMap.put("confidence", jsonObject.getString("confidence"));
                resultMapList.add(resultMap);
            }
        }

        return resultMapList;
    }

    /**
     * 拼音化功能会将非拉丁文字转换为拉丁文字。
     * 拉丁文字基于源语言的发音。例如，Cloud Translation 会将日语字符こんにちは世界拼音化为 Kon'nichiwa sekai。
     *
     * @param sourceLanguage 源语言
     * @param text           待拼音化的文本
     * @return 拼音化的文本
     */
    public static String romanizeText(RomanizeTextSupportLanguageCode sourceLanguage, String text) {
        JSONObject sendJson = new JSONObject();
        sendJson.put("contents", text);
        sendJson.put("source_language_code", sourceLanguage.getLanguageCode());
        Map<String, String> headers = getHeaders();
        headers.put("Content-Type", "application/json");
        logger.debug("请求头: {}", JSON.toJSONString(headers));

        String url = String.format(V3Constant.ROMANIZE_TEXT_URL, V3Constant.PROJECT_ID, V3Constant.LOCATIONS);
        String result = RestMockByProxy.sendPostByBody(url, headers, sendJson.toJSONString(), true);
        JSONObject resultJson = JSONObject.parseObject(result);
        logger.info("响应报文: {}", resultJson.toJSONString());
        JSONArray romanizations = resultJson.containsKey("romanizations") ? resultJson.getJSONArray("romanizations") : new JSONArray();
        if (!romanizations.isEmpty()) {
            // 默认返回第一条结果
            return romanizations.getJSONObject(0).getString("romanizedText");
        }
        return null;
    }
}
